/*
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].
*/

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int cur, start, len;
        cur = start = len = 0;
        while (cur < n) {
            int hit = 0;
            while (cur < n && A[cur] == A[start]) {
                if (hit < 2) {
                    A[len] = A[cur]; 
                    len++; hit++;
                }
                cur++;
            }
            // detect a new block
            start = cur;
        }
        return len;
    }
};
